<?php
namespace Components\User\Sha\Wallet;

class Service {

  /**
   * 加 43
   */
  public function updateIncAmount(
    $fields_index, $user_id, $amount, $type,
    $save1 = null, $save2 = null, $save3 = null, $save4 = null, $save5 = null, $save6 =null,
    $remark = '', $transaction = null
  ) {

    $amount = abs($amount);
    if($amount == 0) { return ['code'=>-1,'msg'=>'数量不能等于0']; }

    $field = Constants::getByIndex('user_wallet_record_fields', $fields_index);
    if(!$field) { return ['code'=>-1,'msg'=>'字段不存在或已删除']; }

    $userWallet = $this -> findFirstById($user_id);
    if($userWallet['code'] != 0) { return $userWallet; }
    
    $fieldModelName = Constants::getByIndex('user_wallet_record_fields_model_name', $fields_index);
    $fieldModelClass = __namespace__.'\\Record\\'.$fieldModelName.'Model';
    $userWalletRecord = new $fieldModelClass([
      'user_id' => $user_id,
      'type' => $type,
      'action' => 43,
      'amount' => $amount,
      'amount_old' => $userWallet['model'] -> $field,
      'create_time' => time(),
      'remark' => $remark
    ]);
    $userWallet['model'] -> $field += $amount;
    $userWalletRecord -> amount_new = $userWallet['model'] -> $field;

    $isTransaction = false;
    if(is_null($transaction)) {
      $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();
      $isTransaction = true;
    }

    try {
      $userWallet['model'] -> setTransaction($transaction);
      if(!$userWallet['model'] -> update()) {
        $msgs = $userWallet['model'] -> getMessages();
        if($isTransaction) { $transaction -> rollback($msgs[0] -> getMessage()); }
        else { throw new \Exception($msgs[0] -> getMessage()); }
      }

      $userWalletRecord -> setTransaction($transaction);
      if(!$userWalletRecord -> create()) {
        $msgs = $userWalletRecord['model'] -> getMessages();
        if($isTransaction) { $transaction -> rollback($msgs[0] -> getMessage()); }
        else { throw new \Exception($msgs[0] -> getMessage()); }
      }

      $isTransaction?$transaction -> commit():'';
    } catch(\Exception $e) {
      return ['code' => -1, 'msg' => $e -> getMessage()];
    }

    return ['code'=>0,'msg'=>'成功'];
  }

  public function rechargeByFieldAndId($fields_index, $user_id, $amount, $operator_index) {
    if($amount > 0) { $action = 43; }
    else { $action = 45; }

    $amount = abs($amount);
    if($amount == 0) { return ['code'=>-1,'msg'=>'数量不能等于0']; }

    $user_id = abs($user_id);
    if($user_id <= 0) { return ['code'=>-1,'msg'=>'用户不存在或已删除']; }

    $field = Constants::getByIndex('user_wallet_record_fields', $fields_index);
    if(!$field) { return ['code'=>-1,'msg'=>'字段不存在或已删除']; }

    $userWallet = $this -> findFirstById($user_id);
    if($userWallet['code'] != 0) { return $userWallet; }

    switch($operator_index) {
      case Record\Constants::OPERATOR_USER:
        $userWalletRecordType = 11101;
        break;
      case Record\Constants::OPERATOR_STAFF:
        $userWalletRecordType = 11201;
        break;
      case Record\Constants::OPERATOR_ADMIN:
        $userWalletRecordType = 11301;
        break;
      default:
        $userWalletRecordType = 0;
    }

    $fieldModelName = Constants::getByIndex('user_wallet_record_fields_model_name', $fields_index);
    $fieldModelClass = __namespace__.'\\Record\\'.$fieldModelName.'Model';
    $userWalletRecord = new $fieldModelClass([
      'user_id' => $user_id,
      'type' => $userWalletRecordType,
      'action' => $action,
      'amount' => $amount,
      'amount_old' => $userWallet['model'] -> $field,
      'create_time' => time(),
      'remark' => '充值'
    ]);

    switch($action) {
      case 43:
        $userWallet['model'] -> $field += $amount;
        break;
      case 45:
        if($userWallet['model'] -> $field < $amount) { return ['code'=>-1,'msg'=>'余额不足']; }
        $userWallet['model'] -> $field -= $amount;
        break;
    }
    $userWalletRecord -> amount_new = $userWallet['model'] -> $field;

    $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();

    try {
      $userWallet['model'] -> setTransaction($transaction);
      if(!$userWallet['model'] -> update()) {
        $msgs = $userWallet['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $userWalletRecord -> setTransaction($transaction);
      if(!$userWalletRecord -> create()) {
        $msgs = $userWalletRecord['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $transaction -> commit();
    } catch(\Exception $e) {
      return ['code' => -1, 'msg' => $e -> getMessage()];
    }

    return ['code' => 0, 'msg' => '充值成功', 'user_wallet' => $userWallet['model']];
  }

  public function transferByFieldsIndexAndToken($fields_index, $from_user_id, $to_user_id, $amount, $operator_index, $save2, $save3, $remark = '') {
    if($amount <= 0) { return ['code'=>-1,'msg'=>'数量不能少于0']; }

    $field = Constants::getByIndex('user_wallet_record_fields', $fields_index);
    if(!$field) { return ['code'=>-1,'msg'=>'字段不存在或已删除']; }

    $fromUserWallet = $this -> findFirstById($from_user_id);
    if($fromUserWallet['code'] != 0) { return $fromUserWallet; }
    if($fromUserWallet['model'] -> $field < $amount) { return ['code'=>-1,'msg'=>'余额不足']; }

    $toUserWallet = $this -> findFirstById($to_user_id);
    if($toUserWallet['code'] != 0) { return $toUserWallet; }

    $fieldModelName = Constants::getByIndex('user_wallet_record_fields_model_name', $fields_index);
    $fieldModelClass = __namespace__.'\\Record\\'.$fieldModelName.'Model';
    $fieldTransferModelName = __namespace__.'\\Record\\'.$fieldModelName.'TransferModel';
    $currentTime = time();

    $fromUserWalletRecord = new $fieldModelClass([
      'user_id' => $from_user_id,
      'type' => 16101,
      'action' => 45,
      'amount' => $amount,
      'amount_old' => $fromUserWallet['model'] -> $field,
      'create_time' => $currentTime,
      'remark' => '转出'
    ]);
    $fromUserWalletTransferRecord = new $fieldTransferModelName([
      'user_id' => $to_user_id
    ]);

    $toUserWalletRecord = new $fieldModelClass([
      'user_id' => $to_user_id,
      'type' => 15101,
      'action' => 43,
      'amount' => $amount,
      'amount_old' => $toUserWallet['model'] -> $field,
      'create_time' => $currentTime,
      'remark' => '转入'
    ]);
    $toUserWalletTransferRecord = new $fieldTransferModelName([
      'user_id' => $from_user_id
    ]);

    $transaction = (new \Phalcon\Mvc\Model\Transaction\Manager()) -> get();

    try {
      $fromUserWallet['model'] -> setTransaction($transaction);
      $fromUserWallet['model'] -> $field -= $amount;
      if(!$fromUserWallet['model'] -> update()) {
        $msgs = $fromUserWallet['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $fromUserWalletRecord -> amount_new = $fromUserWallet['model'] -> $field;
      $fromUserWalletRecord -> setTransaction($transaction);
      if(!$fromUserWalletRecord -> create()) {
        $msgs = $fromUserWalletRecord -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $fromUserWalletTransferRecord -> id = $fromUserWalletRecord -> id;
      $fromUserWalletTransferRecord -> setTransaction($transaction);
      if(!$fromUserWalletTransferRecord -> create()) {
        $msgs = $fromUserWalletTransferRecord -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }
      
      $toUserWallet['model'] -> setTransaction($transaction);
      $toUserWallet['model'] -> $field += $amount;
      if(!$toUserWallet['model'] -> update()) {
        $msgs = $toUserWallet['model'] -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $toUserWalletRecord -> amount_new = $toUserWallet['model'] -> $field;
      $toUserWalletRecord -> setTransaction($transaction);
      if(!$toUserWalletRecord -> create()) {
        $msgs = $toUserWalletRecord -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $toUserWalletTransferRecord -> id = $toUserWalletRecord -> id;
      $toUserWalletTransferRecord -> setTransaction($transaction);
      if(!$toUserWalletTransferRecord -> create()) {
        $msgs = $toUserWalletTransferRecord -> getMessages();
        $transaction -> rollback($msgs[0] -> getMessage());
      }

      $transaction -> commit();
    } catch(\Exception $e) {
      return ['code' => -1, 'msg' => $e -> getMessage()];
    }

    return ['code' => 0, 'msg' => '转账成功', 'user_wallet' => $fromUserWallet['model']];
  }

  public function findFirst($parameters = []) {
    $model = Model::findFirst($parameters);
    if(!$model) { return ['code' => -1, 'msg' => '数据不存在或已删除']; }

    return ['code' => 0, 'model'=>$model];
  }

  public function findFirstById($id) {
    if($id <= 0) { return ['code' => -1, 'msg' => '数据不存在或已删除']; }

    $res = $this -> findFirst(['conditions'=>'user_id = ' . $id]);
    if($res['code'] != 0) { return $this -> createById($id); }

    return $res;
  }

  public function createById($id) {
    $data = ['user_id' => $id];
    foreach(Constants::getByIndex('user_wallet_record_fields') as $filed) { $data[$filed] = 0; }

    return $this -> create($data);
  }

  public function create($data) {
    $model = new Model($data);
    if(!$model -> create()) {
      $messages = $model -> getMessages();
      return ['code' => -1, 'msg' => $messages[0] -> getMessage()];
    }

    return ['code' => 0, 'model'=>$model];
  }
}
